﻿/* 
 * Since 2008 - 2012
 */
package com.hh.bss.talent.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.hibernate.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.hh.bss.auth.client.OnlineManager;
import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.base.BaseSpringController;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.page.Page;
import com.hh.bss.common.page.PageRequest;
import com.hh.bss.customer.entity.Company;
import com.hh.bss.customer.service.CustomerContacterService;
import com.hh.bss.customer.vo.query.CompanyQuery;
import com.hh.bss.project.entity.SearchProjectCcList;
import com.hh.bss.project.entity.SearchProjectCv;
import com.hh.bss.project.service.SearchProjectCcListService;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.entity.CvAttachment;
import com.hh.bss.talent.entity.CvContactDetail;
import com.hh.bss.talent.service.CvAttachmentService;
import com.hh.bss.talent.service.CvContactDetailService;
import com.hh.bss.talent.service.CvService;
import com.hh.bss.talent.vo.query.CvCustomerContacterQuery;
import com.hh.bss.talent.vo.query.CvQuery;
import com.hh.bss.talent.vo.query.CvSuccessQuery;
import com.hh.bss.util.BeanUtils;
import com.hh.bss.util.DateHelper;
import com.hh.bss.util.RandomStringUtil;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.ListRange;

@Controller
public class CvController extends BaseSpringController {

	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;
	private static final ObjectMapper objectMapper = new ObjectMapper();;
	private CvService<Cv, Integer> cvService;

	private CustomerContacterService customerContacterService;

	private SearchProjectCcListService searchProjectCcListService;

	private CvContactDetailService cvContactDetailService;

	private CvAttachmentService cvAttachmentService;

	private Cv cv;
	java.lang.Integer id = null;
	private String[] items;

	/** 通过spring自动注入 */
	public void setCvServiceImpl(CvService service) {
		this.cvService = service;
	}

	/** 通过spring自动注入 */
	public void setCvAttachmentServiceImpl(CvAttachmentService service) {
		this.cvAttachmentService = service;
	}

	public void setSearchProjectCcListService(SearchProjectCcListService searchProjectCcListService) {
		this.searchProjectCcListService = searchProjectCcListService;
	}

	public SearchProjectCcListService getSearchProjectCcListService() {
		return searchProjectCcListService;
	}

	@Autowired
	public void setCustomerContacterService(CustomerContacterService customerContacterService) {
		this.customerContacterService = customerContacterService;
	}

	public void setCvContactDetailServiceImpl(CvContactDetailService service) {
		this.cvContactDetailService = service;
	}

	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/**
	 * ExtGrid使用 列表
	 * 
	 * @throws IOException
	 */
	public void list(HttpServletRequest request, HttpServletResponse response, CvQuery cvQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findCvPage(cvQuery);

		List<Cv> Cvlist = (List) page.getResult();
		ListRange<Cv> resultList = new ListRange<Cv>();
		resultList.setRows(Cvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}
	public String managerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/cvManagerPage.jsp";
		//return "forward:/main.jsp";
	}
    public String cvSuccessPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/cvSuccessPage.jsp";
		//return "forward:/main.jsp";
	}
    public String cvContacterPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/cvContacterPage.jsp";
		//return "forward:/main.jsp";
	}
    public String cvEdit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/cvDetail.jsp";
		//return "forward:/main.jsp";
	}
    public String cvAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/talent/cv/cvInfo.jsp";
		//return "forward:/main.jsp";
	}
    public String cvInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {		
		return "forward:/jsp/talent/cv/cvInfo.jsp";	
	}
    public String selectCvPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/talent/cv/selectCvPage.jsp";
	}

	public void get(HttpServletRequest request, HttpServletResponse response, CvQuery cvQuery) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Cv oldCv = (Cv) cvService.getById(Integer.valueOf(cvQuery.getId()));

			if (oldCv != null)
				result.put("data", oldCv);
			result.put("success", true);
			result.put("msg", "成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void cvlist(HttpServletRequest request, HttpServletResponse response, CvQuery cvQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findCvPage(cvQuery);

		List<Cv> Cvlist = (List) page.getResult();
		ListRange<Cv> resultList = new ListRange<Cv>();
		resultList.setRows(Cvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void cvprojectlist(HttpServletRequest request, HttpServletResponse response, CvQuery cvQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findCvProjectPage(cvQuery);

		List<Cv> Cvlist = (List) page.getResult();
		ListRange<Cv> resultList = new ListRange<Cv>();
		resultList.setRows(Cvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void successcvlist(HttpServletRequest request, HttpServletResponse response, CvSuccessQuery cvSuccessQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findSuccessCvPage(cvSuccessQuery);

		List<SearchProjectCcList> SearchProjectCcListlist = (List) page.getResult();
		ListRange<SearchProjectCcList> resultList = new ListRange<SearchProjectCcList>();
		resultList.setRows(SearchProjectCcListlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void customercontactercvlist(HttpServletRequest request, HttpServletResponse response, CvCustomerContacterQuery cvCustomerContacterQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findCustomerContacterCvPage(cvCustomerContacterQuery);

		List<SearchProjectCcList> SearchProjectCcListlist = (List) page.getResult();
		ListRange<SearchProjectCcList> resultList = new ListRange<SearchProjectCcList>();
		resultList.setRows(SearchProjectCcListlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	/**
	 * extGrid保存
	 * 
	 * @throws IOException
	 */
	public void save(HttpServletRequest request, HttpServletResponse response, Cv cv) throws IOException {
		String type = cv.getCvAttachmentType(); // 人选附件简历类型
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();

				if (onlineUser != null && StringHelper.isEmpty(cv.getCreator())) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(cv, "creator", onlineUser.getUsername());
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					/*
					 * if(cv.getResumeCreator() == null){
					 * cv.setResumeCreator(onlineUser.getUsername()); //简历提供者
					 * 默认为创建人 }
					 */
				}
			}

			if (cv.getCreateDt() == null) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(cv, "createDt", new Date());
				} catch (Exception ex) {
				}
			}
			if (StringHelper.isEmpty(cv.getNameInformer())) {
				cv.setNameInformer(cv.getCreator());
			}
			if (cv.getNameDt() == null) {
				cv.setNameDt(cv.getCreateDt());
			}
			if (cv.getResumeDt() == null) {
				cv.setNameDt(cv.getCreateDt());
			}

			// if
			// (com.tb.bss.util.BeanUtils.isExistsProperty(Cv.class,"birthday"))
			// {
			// try{com.tb.bss.util.BeanUtils.setProperty(cv,"birthday",new
			// Date());}catch(Exception ex){}
			// }
			cv.setCvFrom(ConstantDic.CvFrom_H);
			/*
			 * ---------- 开始处理文件上传 ----------
			 */
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartHttpServletRequest.getFile("imageupload");

			MultipartFile multipartFileCv = multipartHttpServletRequest.getFile("uploadFile"); // 简历
			String originalFileName = multipartFile.getOriginalFilename();
			// SimpleDateFormat dateformat = new
			// SimpleDateFormat("yyyy/MM/dd/HH");
			String logoPathDir = "/uploadfile/" + DateHelper.toString(new Date(), "yyyyMMdd") + "/";
			String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);

			File file = new File(logoRealPathDir);
			if (!file.exists()) {
				file.mkdir();
			}
			try {
				System.out.println(file.getAbsolutePath());

				if (multipartHttpServletRequest != null && multipartFile != null && !multipartFile.isEmpty()) {
					String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
					originalFileName = DateHelper.toString(new Date(), "HHmmss") + RandomStringUtil.getString(3) + "." + suffix;
					File filelogo = new File(logoRealPathDir + "/" + originalFileName);
					try {
						multipartFile.transferTo(filelogo); // 将文件写入到指定的目录
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}

				}

				// FileOutputStream fileOutputStream = new FileOutputStream(file
				// + "/"+originalFileName
				// );
				// fileOutputStream.write(multipartFile.getBytes());
				// fileOutputStream.flush();
				// fileOutputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
				result.put("success", false);
				result.put("msg", e.getMessage());
			}
			cv.setLogo(logoPathDir + originalFileName);
			String contact_json = request.getParameter("contact_data").toString();
			List<CvContactDetail> contact_list = objectMapper.readValue(contact_json, new TypeReference<List<CvContactDetail>>() {
			});
			// cvService.save(cv);
			// cv.setMobile(contact_json)
			cv.setCv_status_str("T"); // 设置简历状态
			if (!cvService.checkContact(cv, contact_list)) {
			} else {
				result.put("failure", true);
				result.put("msg", "人才重复,请检查   邮件  手机  是否存在相同的记录.");
				outJson(response, result);
				return;

			}
			// 如果 不选 简历提供者 设置简历提供者 为上传者
			if (multipartFileCv != null && !multipartFileCv.isEmpty()) {
				if (StringUtils.isEmpty(cv.getResumeInformer())) {
					cv.setResumeInformer(cv.getCreator());
				}
			}
			// 开始检查
			cvService.saveWithContentList(cv, contact_list);
			if (multipartFileCv != null && !multipartFileCv.isEmpty()) {
				if (StringUtils.isNotEmpty(type)) {
					CvAttachment cvAttachment = new CvAttachment();
					cvAttachment.setCvId(cv.getId());
					cvAttachment.setCreator(cv.getCreator());
					cvAttachment.setCreateDt(new Date());
					cvAttachment.setType(type);
					cvAttachmentService.saveFile(multipartHttpServletRequest, request, cvAttachment);
					cvAttachmentService.save(cvAttachment);
					cvService.updateCvStatus(cv.getId());
				}
			}
			// 检查是否上传附件
			result.put("success", true);
			result.put("msg", "添加成功!");

			// //如果选择了现任公司 和 人选类型 则在客户联系人中出现
			// i//f(cv.getCompanyId() != null && ""cv.getCvType())
			/*
			 * if( (cv.getCompanyId() != null && cv.getCompanyId()>0) &&
			 * StringHelper.isNotEmpty(cv.getCvType())){ //根据公司Id 找到客户公司Id
			 * Integer custId =
			 * customerContacterService.getCustIdByCompanyId(cv.getCompanyId());
			 * if(custId != null){
			 * //cv.cv_type从常量选择，人才类型：2020:BD联系人，2021:合作决策人，2022:职位联系人，
			 * //2023:收款联系人，2024:成功候选人（录入offer后更新），2025 ：普通候选人 //对应客户联系人
			 * //CT-BD联系人 CP-合作决策人 JC-职位联系人 FC-收款联系人 Map<Integer,String>
			 * cvTypeMap = new HashMap<Integer, String>(); cvTypeMap.put(2020,
			 * "CT"); //BD联系人 cvTypeMap.put(2021, "CP"); //合作决策人
			 * cvTypeMap.put(2022, "JC"); //职位联系人 cvTypeMap.put(2023, "FC");
			 * //收款联系人 Integer cvTypeCode = Integer.valueOf(cv.getCvType());
			 * if(cvTypeMap.containsKey(cvTypeCode)){ //检查是否存在 同类型的客户联系人. //int
			 * count =
			 * customerContacterService.checkCustomerRoleCount(custId.toString
			 * (), cvTypeMap.get(cvTypeCode)); //if(count<1 && count != -1){
			 * CustomerContacter contacter = new CustomerContacter();
			 * contacter.setCreateDt(cv.getCreateDt());
			 * contacter.setCreator(cv.getCreator());
			 * contacter.setCvId(cv.getId());
			 * contacter.setRole(cvTypeMap.get(cvTypeCode));
			 * contacter.setCustId(custId); contacter.setComment("系统自动添加");
			 * customerContacterService.save(contacter); //客户联系人 //}
			 * 
			 * }
			 * 
			 * }
			 * 
			 * }
			 */
			if (cv.getCompany() != null && !"".equals(cv.getCompany())) {
				Integer companyId = cvService.getCompanyId(cv.getCompany());
				if (companyId != null && !"".equals(companyId)) {
					boolean isexist = cvService.isExistSearchProjectCv(cv.getId(), companyId.toString());
					if (isexist) {
						SearchProjectCv search = new SearchProjectCv();
						search.setCvId(cv.getId());
						search.setCreator(cv.getCreator());
						search.setCreateDt(cv.getCreateDt());
						search.setCompanyId(new Integer(companyId));
						search.setProjectId(0);
						this.cvService.saveCompanyTree(search);
					}
				}
			}

		}

		catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid修改
	 * 
	 * @throws IOException
	 */
	public void update(HttpServletRequest request, HttpServletResponse response, Cv cv) throws IOException {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();
		// 如果 简历完整度选择的是 重复 --8 直接更新 简历完整度
		Map<String, String> repMap = new HashMap<String, String>();
		repMap.put("7", "不能处理");
		repMap.put("8", "重复 ");
		repMap.put("9", "SC要求删除");
		// repMap.put("10", "已经处理");
		repMap.put("-1", "申请删除");
		try {

			Cv oldcv = (Cv) cvService.getById(cv.getId());
			String contact_json = request.getParameter("contact_data");

			List<CvContactDetail> contact_list = objectMapper.readValue(contact_json, new TypeReference<List<CvContactDetail>>() {
			});
			if (StringUtils.isNotEmpty(cv.getIntegrity())) {
				if (cvService.checkUser(cv, contact_list)) {
					result.put("failure", true);
					result.put("msg", "人才重复,请检查 姓名 邮件  是否存在相同的记录.");
					outJson(response, result);
					return;
				}
			}

			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(Cv.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oldcv, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(Cv.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oldcv, "modifiedDt", new Date());
				} catch (Exception ex) {
				}
			}

			if (StringUtils.isNotEmpty(cv.getIntegrity())) {
				if (repMap.containsKey(cv.getIntegrity())) {
					oldcv.setIntegrity(cv.getIntegrity());
					cvService.update(oldcv);
					result.put("success", true);
					result.put("msg", "修改成功!");
					outJson(response, result);
					return;
				}
			}

			bind(request, oldcv);

			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartHttpServletRequest.getFile("imageupload");
			String originalFileName = multipartFile.getOriginalFilename();
			// SimpleDateFormat dateformat = new
			// SimpleDateFormat("yyyy/MM/dd/HH");
			String logoPathDir = "/uploadfile/" + DateHelper.toString(new Date(), "yyyyMMdd") + "/";
			String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);

			File file = new File(logoRealPathDir);
			if (!file.exists()) {
				file.mkdir();
			}
			try {
				// System.out.println(file.getAbsolutePath());

				if (multipartHttpServletRequest != null && multipartFile != null && !multipartFile.isEmpty()) {
					String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
					originalFileName = DateHelper.toString(new Date(), "HHmmss") + RandomStringUtil.getString(3) + "." + suffix;
					File filelogo = new File(logoRealPathDir + "/" + originalFileName);
					try {
						multipartFile.transferTo(filelogo); // 将文件写入到指定的目录
						System.out.println(filelogo.getPath());
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				// FileOutputStream fileOutputStream = new FileOutputStream(file
				// + "/"+originalFileName
				// );
				// fileOutputStream.write(multipartFile.getBytes());
				// fileOutputStream.flush();
				// fileOutputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
				responseMap.put("success", false);
				responseMap.put("msg", e.getMessage());
			}

			if (originalFileName != null && !originalFileName.equals("")) {
				oldcv.setLogo(logoPathDir + originalFileName);
			}

			// if(!cvService.checkUser(oldcv, contact_list)){ //判断用户是否重复
			cvService.updateWithContactList(oldcv, contact_list);
			result.put("success", true);
			result.put("msg", "修改成功!");

			// //如果选择了现任公司 和 人选类型 则在客户联系人中出现
			// 选择的人选类型 如果是客户联系人 把它添加到客户联系人中 并检查客户联系人是否存在
			// i//f(cv.getCompanyId() != null && ""cv.getCvType())
			/*
			 * if( (oldcv.getCompanyId() != null && oldcv.getCompanyId()>0) &&
			 * StringHelper.isNotEmpty(oldcv.getCvType())){ //根据公司Id 找到客户公司Id
			 * Integer custId =
			 * customerContacterService.getCustIdByCompanyId(oldcv
			 * .getCompanyId()); if(custId != null){
			 * //cv.cv_type从常量选择，人才类型：2020:BD联系人，2021:合作决策人，2022:职位联系人，
			 * //2023:收款联系人，2024:成功候选人（录入offer后更新），2025 ：普通候选人 //对应客户联系人
			 * //CT-BD联系人 CP-合作决策人 JC-职位联系人 FC-收款联系人 Map<Integer,String>
			 * cvTypeMap = new HashMap<Integer, String>(); cvTypeMap.put(2020,
			 * "CT"); //BD联系人 cvTypeMap.put(2021, "CP"); //合作决策人
			 * cvTypeMap.put(2022, "JC"); //职位联系人 cvTypeMap.put(2023, "FC");
			 * //收款联系人 Integer cvTypeCode = Integer.valueOf(oldcv.getCvType());
			 * if(cvTypeMap.containsKey(cvTypeCode)){ //检查是否存在 同类型的客户联系人. //int
			 * count =
			 * customerContacterService.checkCustomerRoleCount(custId.toString
			 * (), cvTypeMap.get(cvTypeCode)); //if(count<1 && count != -1){
			 * CustomerContacter contacter = new CustomerContacter();
			 * contacter.setCreateDt(new Date());
			 * contacter.setCreator(oldcv.getCreator());
			 * contacter.setCvId(oldcv.getId());
			 * contacter.setRole(cvTypeMap.get(cvTypeCode));
			 * contacter.setCustId(custId); contacter.setComment("系统自动添加");
			 * //customerContacterService.save(contacter); //客户联系人
			 * customerContacterService.saveOrUpdate(contacter); //} } } }
			 */

			/*
			 * if(cv.getCompany() !=null && !"".equals(cv.getCompany())){
			 * Integer companyId = cvService.getCompanyId(cv.getCompany());
			 * if(companyId != null && !"".equals(companyId)){ boolean isexist =
			 * cvService.isExistSearchProjectCv(cv.getId(),
			 * companyId.toString());
			 * System.out.println("======="+isexist+"=========="); if(isexist){
			 * SearchProjectCv search = new SearchProjectCv();
			 * search.setCvId(cv.getId()); search.setCreator(cv.getCreator());
			 * search.setCreateDt(cv.getCreateDt()); search.setCompanyId(new
			 * Integer(companyId)); search.setProjectId(0);
			 * this.cvService.saveCompanyTree(search); } } }
			 */

			/*
			 * }else{ result.put("failure", true);
			 * 
			 * }
			 */
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * 处理简历
	 * 
	 * @param request
	 * @param response
	 * @param cv
	 */
	public void solved(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineManager onlineManager = new OnlineManager(request, response);
			OnlineUser onlineUser = onlineManager.getOnlineUser();
			String ids = request.getParameter("ids");
			String integrity = request.getParameter("integrity");
			String[] idArray = ids.split(",");
			for (String cvId : idArray) {
				Cv cv = this.cvService.getById(Integer.valueOf(cvId));
				cv.setIntegrity(integrity);
				cv.setModifier(onlineUser.getUsername());
				cv.setModifiedDt(new Date());
				this.cvService.update(cv);
			}
		} catch (NumberFormatException e) {
			result.put("failure", true);
			result.put("msg", "数字格式有误");
			e.printStackTrace();
		} catch (DataAccessException e) {
			result.put("failure", true);
			result.put("msg", "数据访问异常,请联系管理员");
			e.printStackTrace();
		}
		result.put("success", true);
		result.put("msg", "修改成功!");
		outJson(response, result);

	}

	/**
	 * 人才信息批量修改
	 * 
	 * @param req
	 * @param res
	 * @return
	 */
	public void batchupdate(HttpServletRequest request, HttpServletResponse response, Cv cv) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		String cvIds = request.getParameter("cvIds");
		if (cvIds != null && cvIds.length() > 0) {
			try {
				OnlineManager onlineManager = super.getOnlineManager(request, response);
				OnlineUser onlineUser = null;
				if (onlineManager != null) {
					onlineUser = onlineManager.getOnlineUser();
				}
				String[] cvIdArr = cvIds.split(",");
				for (String cvId : cvIdArr) {
					Integer id = Integer.parseInt(cvId);
					Cv oldCv = (Cv) cvService.getById(id);
					logger.info("人选标签:" + oldCv.getCvTag());
					logger.info("人选类别" + oldCv.getCvType());
					if (cv.getIndustry() != null && cv.getIndustry() > 0) { // 行业
						oldCv.setIndustry(cv.getIndustry());
					}
					if (StringUtils.isNotEmpty(cv.getCvType())) { // 人选类别
						oldCv.setCvType(cv.getCvType());
					}
					if (StringUtils.isNotEmpty(cv.getCvTag())) { // 人选标签
						oldCv.setCvTag(cv.getCvTag());
					}
					if (StringUtils.isNotEmpty(cv.getNationality())) { // 国籍
						oldCv.setNationality(cv.getNationality());
					}
					if (cv.getFunction() != null && cv.getFunction() > 0) { // 职能
						oldCv.setFunction(cv.getFunction());
					}
					if (cv.getRegisterLocation() != null && cv.getRegisterLocation() > 0) { // 所在城市
						oldCv.setRegisterLocation(cv.getRegisterLocation());
					}
					if (StringUtils.isNotEmpty(cv.getCvFlLevel())) { // 外语能力
						oldCv.setCvFlLevel(cv.getCvFlLevel());
					}
					if (cv.getCurrentSalary() != null && cv.getCurrentSalary() > 0) {// 年薪范围
						oldCv.setCurrentSalary(cv.getCurrentSalary());
					}
					if (cv.getDegree() != null && cv.getDegree() > 0) { // 学历
						oldCv.setDegree(cv.getDegree());
					}
					if (cv.getWorkYear() != null && cv.getWorkYear() > 0) { // 开始工作年份
						oldCv.setWorkYear(cv.getWorkYear());
					}
					if (cv.getMarried() != null) { // 婚姻状况
						oldCv.setMarried(cv.getMarried());
					}
					if (cv.getLevel() != null) { // 职级
						oldCv.setLevel(cv.getLevel());
					}
					if (cv.getIntegrity() != null) { // 简历完善度
						oldCv.setIntegrity(cv.getIntegrity());
					}
					if (onlineUser != null && BeanUtils.isExistsProperty(Company.class, "modifier")) {
						try {
							BeanUtils.setProperty(oldCv, "modifier", onlineUser.getUsername());
						} catch (Exception ex) {
						}
					}
					if (BeanUtils.isExistsProperty(Company.class, "modifiedDt")) {
						try {
							BeanUtils.setProperty(oldCv, "modifiedDt", new Date());
						} catch (Exception ex) {
						}
					}
					cvService.update(oldCv);
					// cvService.
				}
				result.put("success", true);
				result.put("msg", "修改成功!");

			} catch (Exception e) {
				result.put("failure", true);
				result.put("msg", e.getMessage());
				e.printStackTrace();
			}

		} else {
			result.put("failure", true);
			result.put("msg", "人选ID不能为空.");
		}

		outJson(response, result);

	}

	public ModelAndView exporthtml(HttpServletRequest req, HttpServletResponse res) {
		String cv_id = req.getParameter("id");
		logger.info(cv_id);
		Map<String, Object> cvMap = cvService.getCvHtml(Integer.parseInt(cv_id));
		ModelAndView mv = new ModelAndView();
		mv.setViewName("freemarker");
		mv.addObject("cvMap", cvMap);
		// System.out.println(mv.toString());
		res.setCharacterEncoding("UTF-8");
		return mv;
	}

	/**
	 * extGrid删除
	 * 
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			StringBuffer info = new StringBuffer();
			for (int i = 0; i < idarray.length; i++) {
				java.lang.Integer id = new java.lang.Integer((String) idarray[i]);
				// 检查是否有Offer,如果有 不能删除
				if (!cvService.hasAccountPn(id)) {
					cvService.removeById(id);
					cvContactDetailService.removeByCvId(id);
				} else {
					info.append(id).append(",");
				}

			}
			if (info.length() > 0) {
				StringBuffer st = new StringBuffer("人才编号:");
				st.append(info).append("存在Offer,不能删除!");
				info = st;
				st = null;
			}
			result.put("success", true);
			result.put("msg", "删除成功!" + info);
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public ModelAndView extupload(HttpServletRequest req, HttpServletResponse res) {
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		// view.setContentType("text/html");
		// view.setContentType("application/x-javascript");
		// view.setContentType("application/json");
		Map<String, Object> responseMap = new HashMap<String, Object>();
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) req;
		MultipartFile multipartFile = multipartHttpServletRequest.getFile("uploadFile");
		String originalFileName = multipartFile.getOriginalFilename();
		// SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");
		String logoPathDir = "/uploadfile/";
		String logoRealPathDir = req.getSession().getServletContext().getRealPath(logoPathDir);

		File file = new File(logoRealPathDir);
		if (!file.exists()) {
			file.mkdir();
		}
		try {
			System.out.println(file.getAbsolutePath());
			FileOutputStream fileOutputStream = new FileOutputStream(file + "/uploadFile" + originalFileName.substring(originalFileName.lastIndexOf('.'), originalFileName.length()));
			fileOutputStream.write(multipartFile.getBytes());
			fileOutputStream.flush();
			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			responseMap.put("success", false);
			responseMap.put("msg", e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			responseMap.put("success", false);
			responseMap.put("msg", e.getMessage());
		}
		// res.setContentType("text/html");
		view.setContentType("text/html");
		res.setContentType("text/html");
		responseMap.put("success", true);
		responseMap.put("msg", "上传成功");
		ModelAndView mav = new ModelAndView(view, responseMap);
		return mav;
	}

	public void CheckCv(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// String cvName = request.getParameter("cvName");
			String contact_json = request.getParameter("contact_data").toString();
			List<CvContactDetail> contact_list = objectMapper.readValue(contact_json, new TypeReference<List<CvContactDetail>>() {
			});
			Cv cv = new Cv(); // 人才
			// cv.setCvName(cvName);
			// bind(request,cv);
			// cv.setId(value)
			if (!cvService.checkContact(cv, contact_list)) { // 开始检查
				result.put("success", true);
			} else {
				result.put("success", false);
			}
		} catch (Exception e) {
			result.put("failure", true);
			// result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * 导出简历
	 * 
	 * @param req
	 * @param res
	 */
	public void down(HttpServletRequest request, HttpServletResponse response) {
		InputStream fis = null;
		OnlineUser onlineUser = null;
		OnlineManager onlineManager = super.getOnlineManager(request, response);
		if (onlineManager != null) {
			onlineUser = onlineManager.getOnlineUser();
		}
		String type = request.getParameter("type"); // type=1，中文,type=2英文，默认是中文
		Integer cvId = Integer.valueOf(request.getParameter("cvId")).intValue(); // 人选Id
		File file = null;
		if ("1".equals(type)) { // 中文简历
			file = cvService.genRecomDoc(request, onlineUser, cvId);
		} else if ("2".equals(type)) { // 英文简历
			file = cvService.genRecomDocEn(request, onlineUser, cvId);
		}
		try {
			if (file == null || !file.exists())
				return;
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			// String ext = filename.substring(filename.lastIndexOf(".") +
			// 1).toUpperCase();
			// 以流的形式下载文件。
			fis = new BufferedInputStream(new FileInputStream(file));
			byte[] data = new byte[fis.available()];
			fis.read(data);
			fis.close();
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
			response.addHeader("Content-Length", "" + data.length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
			outputStream.write(data);
			outputStream.flush();
			outputStream.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		}

		/*
		 * String cv_id = req.getParameter("cvId"); //logger.info(cv_id);
		 * Map<String,Object> cvMap =
		 * cvService.getCvHtml(Integer.parseInt(cv_id)); ModelAndView mv = new
		 * ModelAndView(); mv.setViewName("freemarker");
		 * mv.addObject("cvMap",cvMap); //System.out.println(mv.toString());
		 * res.setCharacterEncoding("UTF-8"); //return mv;
		 */}

	/**
	 * 从excel 中 导入 人选
	 * 
	 * @param request
	 * @param response
	 * @param cvQuery
	 * @throws IOException
	 */
	public void importcv(HttpServletRequest request, HttpServletResponse response, Cv cv) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 设置创建用户和创建时间
			OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && BeanUtils.isExistsProperty(Cv.class, "creator")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(cv, "creator", onlineUser.getUsername());
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}

			if (BeanUtils.isExistsProperty(Cv.class, "createDt")) {
				try {
					BeanUtils.setProperty(cv, "createDt", new Date());
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			// cvService

			cvService.importCvFromExcel("C:\\人选导入20130417.xls");
			result.put("success", true);
			result.put("msg", "导入成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * 已删除 和 申请删除
	 * 
	 * @param request
	 * @param response
	 * @param cv
	 */

	public void deletelist(HttpServletRequest request, HttpServletResponse response, CvQuery cvQuery) {

		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findCvDelPage(cvQuery);

		List<Cv> Cvlist = (List) page.getResult();
		ListRange<Cv> resultList = new ListRange<Cv>();
		resultList.setRows(Cvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);

	}

	/**
	 * 简历合并
	 * 
	 * @param request
	 * @param response
	 * @param cvQuery
	 * @throws IOException
	 */
	public void cvmergelist(HttpServletRequest request, HttpServletResponse response, CvQuery cvQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findCvMergePage(cvQuery);

		List<Cv> Cvlist = (List) page.getResult();
		ListRange<Cv> resultList = new ListRange<Cv>();
		resultList.setRows(Cvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void cvmerge(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String cvIds = request.getParameter("cvIds");
		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(cvIds)) {
			if (cvIds.contains(id)) {
				cvIds = cvIds.replace(id, "");
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			cvService.cvMerger(id, cvIds);
			result.put("success", true);
			result.put("msg", "合并成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void industryupdate(HttpServletRequest request, HttpServletResponse response, Cv cv) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Cv oldcv = (Cv) cvService.getById(cv.getId());

			bind(request, oldcv);
			// 设置修改用户和修改时间
			OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && BeanUtils.isExistsProperty(Cv.class, "modifier")) {
					try {
						BeanUtils.setProperty(oldcv, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}

			if (BeanUtils.isExistsProperty(Cv.class, "modifiedDt")) {
				try {
					BeanUtils.setProperty(oldcv, "modifiedDt", new Date());
				} catch (Exception ex) {
				}
			}

			// companyService.update(oldcompany);
			this.cvService.update(oldcv);
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	public void updateindustry(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		OnlineManager onlineManager = super.getOnlineManager(request, response);
		OnlineUser onlineUser = null;
		if (onlineManager != null) {
			onlineUser = onlineManager.getOnlineUser();
		}
		String data_json = request.getParameter("data").toString();
		List<CvQuery> cvList = objectMapper.readValue(data_json, new TypeReference<List<CvQuery>>() {
		});
		if (cvList != null && cvList.size() > 0) {
			for (CvQuery cvQuery : cvList) {
				Cv cv = this.cvService.getById(Integer.valueOf(cvQuery.getId()));
				cv.setFunction(Integer.valueOf(cvQuery.getFunction()));
				cv.setIndustry(Integer.valueOf(cvQuery.getIndustry()));
				cv.setModifier(onlineUser.getUsername());
				cv.setModifiedDt(new Date());
				cv.setIntegrity("10");
				// cv.setIndustry(10);
				this.cvService.update(cv);
			}
		}
		result.put("success", true);
		result.put("msg", "修改成功!");
		outJson(response, result);
	}

	public void sameofdellist(HttpServletRequest request, HttpServletResponse response, CvQuery cvQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = cvService.findSameOfDelCvPage(cvQuery);

		List<Cv> Cvlist = (List) page.getResult();
		ListRange<Cv> resultList = new ListRange<Cv>();
		resultList.setRows(Cvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	public void recover(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		cvService.recoverCv(ids);
		cvContactDetailService.recoverByCvId(ids);
		result.put("success", true);
		result.put("msg", "恢复成功!");
		outJson(response, result);

	}

}
